<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const toolId = ref(route.params.id as string | undefined)
const isEditMode = ref(!!toolId.value)

const form = ref({
  name: '',
  description: '',
  target_api_url: '',
  openapi_spec_content: '',
  authentication_headers: {}, // Simplified for now
  filter_dsl: ''
})

const API_BASE_URL = '/api/v1'

onMounted(async () => {
  if (isEditMode.value) {
    try {
      const response = await axios.get(`${API_BASE_URL}/tools/${toolId.value}`)
      form.value = response.data
    } catch (error) {
      ElMessage({
        message: '获取工具详情失败。',
        type: 'error',
        duration: 3000,
        showClose: true,
        grouping: true
      })
      console.error(error)
    }
  }
})

const handleSubmit = async () => {
  try {
    if (isEditMode.value) {
      await axios.put(`${API_BASE_URL}/tools/${toolId.value}`, form.value)
      ElMessage({
        message: '工具更新成功！',
        type: 'success',
        duration: 3000,
        showClose: true,
        grouping: true
      })
    } else {
      await axios.post(`${API_BASE_URL}/tools/`, form.value)
      ElMessage({
        message: '工具创建成功！',
        type: 'success',
        duration: 3000,
        showClose: true,
        grouping: true
      })
    }
    router.push('/') // Redirect to dashboard after submission
  } catch (error) {
    ElMessage({
      message: '操作失败。',
      type: 'error',
      duration: 3000,
      showClose: true,
      grouping: true
    })
    console.error(error)
  }
}
</script>

<template>
  <div>
    <h1>{{ isEditMode ? '编辑工具' : '创建新工具' }}</h1>
    <el-form :model="form" label-width="120px" label-position="top">
      <el-form-item label="名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
      <el-form-item label="目标 API URL">
        <el-input v-model="form.target_api_url" />
      </el-form-item>
      <el-form-item label="OpenAPI 规范内容">
        <el-input v-model="form.openapi_spec_content" type="textarea" :rows="15" />
      </el-form-item>
      <!-- Simplified fields for auth and filter for now -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">
          {{ isEditMode ? '保存更新' : '立即创建' }}
        </el-button>
        <el-button @click="router.push('/')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
h1 {
  color: #E6EDF3;
  margin-bottom: 2rem;
}
</style>
